<template>
  <div class="loginBox">
    <el-card class="box-card">
      <div class="content">
        <el-row>
          <el-col :span="24"><div class="grid-content bg-purple-dark"><img src="@/assets/imgs/logo.jpg" style="width:80px;"/></div></el-col>
        </el-row>
        <h3 v-if="isLogin">登录</h3>
        <h3 v-else>注册</h3>
        <br>

        <el-form
            ref="loginFormRef"
            v-if="isLogin"
            :model="loginForm"
            :rules="loginRules"
            label-width="80px"
        >
          <el-form-item label="账号" prop="username">
            <el-input v-model="loginForm.username" type="text" autocomplete="off" />
          </el-form-item>
          <el-form-item label="密码" prop="password">
            <el-input v-model="loginForm.password" type="password" autocomplete="off" />
          </el-form-item>
          <el-form-item label="验证码" prop="captcha">
            <el-row>
              <el-col :span="12">
                <el-input v-model="loginForm.captcha" type="text" autocomplete="off" />
              </el-col>
              <el-col :span="12">
                <img :src="captchaUrl" @click="refreshCaptcha" alt="captcha" />
              </el-col>
            </el-row>
          </el-form-item>
          <br>

          <el-form-item style="margin-left: 30px">
            <el-button type="primary" @click="submitForm">登录</el-button>
            &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
            <el-button @click="toggleForm">注册</el-button>
          </el-form-item>
        </el-form>

        <el-form
            ref="registerFormRef"
            v-else
            :model="registerForm"
            :rules="registerRules"
            label-width="80px"
        >
          <el-form-item label="账号" prop="username">
            <el-input v-model="registerForm.username" type="text" autocomplete="off" />
          </el-form-item>
          <el-form-item label="密码" prop="password">
            <el-input v-model="registerForm.password" type="password" autocomplete="off" />
          </el-form-item>
          <el-form-item label="确认密码" prop="confirmPass">
            <el-input v-model="registerForm.confirmPass" type="password" autocomplete="off" />
          </el-form-item>
          <el-form-item label="邮箱" prop="email">
            <el-input v-model="registerForm.email" type="email" autocomplete="off" />
          </el-form-item>
          <el-form-item style="margin-left: 30px">
            <el-button type="primary" @click="submitRegisterForm">注册</el-button>
            &nbsp;&nbsp;
            <el-button @click="toggleForm">返回登录</el-button>
          </el-form-item>
        </el-form>
      </div>
    </el-card>
  </div>
</template>

<script setup>
import { reactive, ref, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { useRouter } from "vue-router"
import request from '@/utils/request'

const router = useRouter()

const loginFormRef = ref()
const registerFormRef = ref()
const isLogin = ref(true)
const captchaUrl = ref('')

// 初始化表单数据
const loginForm = reactive({
  username: '',
  password: '',
  captcha: ''
})

const registerForm = reactive({
  username: '',
  password: '',
  confirmPass: '',
  email: ''
})

// 表单验证规则
const loginRules = reactive({
  username: [
    { required: true, message: '必须填写账号', trigger: 'blur' },
    { min: 3, max: 20, message: '账号长度为3-20', trigger: 'blur' },
  ],
  password: [
    { required: true, message: '必须填写密码', trigger: 'blur' },
    { pattern: /^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]{6,}$/, message: '密码必须是数字和字母相结合，长度至少6位！', trigger: 'blur' },
  ],
  captcha: [
    { required: true, message: '必须填写验证码', trigger: 'blur' }
  ]
})

const registerRules = reactive({
  username: [
    { required: true, message: '必须填写账号', trigger: 'blur' },
    { min: 3, max: 20, message: '账号长度为3-20', trigger: 'blur' },
  ],
  password: [
    { required: true, message: '必须填写密码', trigger: 'blur' },
    { pattern: /^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]{6,}$/, message: '密码必须是数字和字母相结合，长度至少6位！', trigger: 'blur' },
  ],
  confirmPass: [
    { required: true, message: '必须确认密码', trigger: 'blur' },
    { validator: (rule, value, callback) => {
        if (value !== registerForm.password) {
          callback(new Error('两次输入的密码不一致'))
        } else {
          callback()
        }
      }, trigger: 'blur' }
  ]
})

// 获取验证码
const refreshCaptcha = () => {
  captchaUrl.value = `http://localhost:8089/sys/user/captcha?t=${new Date().getTime()}`
}

onMounted(() => {
  refreshCaptcha()
})

// 登录表单提交
const submitForm = () => {
  loginFormRef.value.validate((valid) => {
    if (valid) {
      request({
        url: '/sys/user/login',
        method: 'GET',
        params: loginForm
      }).then(res => {
        if (res.data.errorCode === '200') {
          sessionStorage.setItem('loginUser', JSON.stringify(loginForm))
          sessionStorage.setItem('token', res.data.data) // 存储 token
          const userType = res.data.msg;
          if (userType === 'admin') {
            router.push('/main/index')
          } else if (userType === 'common') {
            router.push('/main3/index')
          } else if (userType === 'auditor') {
            router.push('/main2/index')
          }
        } else {
          ElMessage({
            message: '请求失败，密码或验证码错误',
            type: 'error'
          })
        }
      }).catch(error => {
        ElMessage({
          message: '请求失败，密码或验证码错误',
          type: 'error'
        })
      })
    } else {
      ElMessage({
        message: '请填写完整表单',
        type: 'warning'
      })
    }
  })
}

// 注册表单提交
const submitRegisterForm = () => {
  registerFormRef.value.validate((valid) => {
    if (valid) {
      request({
        url: '/sys/user/add',
        method: 'POST',
        data: registerForm
      }).then(res => {
        if (res.data.errorCode === '200') {
          ElMessage({
            message: '注册成功，请登录',
            type: 'success'
          })
          isLogin.value = true
        } else {
          ElMessage({
            message: res.data.msg,
            type: 'error'
          })
        }
      }).catch(error => {
        ElMessage({
          message: '请求失败，请重试',
          type: 'error'
        })
      })
    } else {
      ElMessage({
        message: '请填写完整表单',
        type: 'warning'
      })
    }
  })
}

// 切换表单
const toggleForm = () => {
  isLogin.value = !isLogin.value
  refreshCaptcha()
}
</script>

<style scoped>
.loginBox {
  display: flex;
  justify-content: center;
  align-items: center;
  position: absolute;
  left: 0;
  top: 0;
  height: 100%;
  width: 100%;
  background-image: url("../assets/imgs/loginBg.jpg");
  background-size: cover;
}
.box-card {
  width: 400px;
}


body {
  height: 100%;
  /* CSS3 抗锯齿形 让文字显示的更加清晰 */
  -webkit-font-smoothing: antialiased;
  background-color: #ffffff;
  color: #000000;
}
/* 把我们所有标签的内外边距清零 */
* {
  margin: 0;
  padding: 0;
  /* css3盒子模型 */
  box-sizing: border-box;
}
/* em 和 i 斜体的文字不倾斜 */
em,
i {
  font-style: normal;
}
/* 去掉li 的小圆点 */
li {
  list-style: none;
}

img {
  /* border 0 照顾低版本浏览器 如果 图片外面包含了链接会有边框的问题 */
  border: 0;
  /* 取消图片底侧有空白缝隙的问题 */
  vertical-align: middle;
}

button {
  /* 当我们鼠标经过button 按钮的时候，鼠标变成小手 */
  cursor: pointer;
}

a {
  color: #666;
  text-decoration: none;
}

a:hover {
  color: #2378cb;
}

button,
input {
  /* "\5B8B\4F53" 就是宋体的意思 这样浏览器兼容性比较好 */
  font-family: Microsoft YaHei, Heiti SC, tahoma, arial, Hiragino Sans GB,
  '\5B8B\4F53', sans-serif;
  /* 默认有灰色边框我们需要手动去掉 */
  border: 0;
  outline: none;
}

.code {
  text-align: center;
  margin-bottom: 10px;
}

</style>
